#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent, const QString& ip, const QString& port)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , networkManager(new QNetworkAccessManager(this))
    , sip(ip)
    , sport(port)
{
    ui->setupUi(this);

    ui->cardImage->setMinimumSize(300, 380);
    ui->cardImage->setMaximumSize(300, 380);

    connect(ui->balanceButton, &QPushButton::clicked, this, &MainWindow::handleBalance);
    connect(ui->transferButton, &QPushButton::clicked, this, &MainWindow::handleTransfer);
    connect(ui->depositButton, &QPushButton::clicked, this, &MainWindow::handleDeposit);
    connect(ui->withdrawButton, &QPushButton::clicked, this, &MainWindow::handleWithdraw);
    connect(networkManager, &QNetworkAccessManager::finished, this, &MainWindow::handleNetworkReply);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::handleBalance()
{
    bool ok;
    QString cardNumber = QInputDialog::getText(this, "余额查询", "输入卡号：", QLineEdit::Normal, "", &ok);
    if (!ok || cardNumber.isEmpty()) return;

    QString password = QInputDialog::getText(this, "余额查询", "输入密码：", QLineEdit::Password, "", &ok);
    if (!ok || password.isEmpty()) return;

    QJsonObject json;
    json["card_number"] = cardNumber;
    json["password"] = password;

    sendRequest("/balance", json);
}

void MainWindow::handleTransfer()
{
    bool ok;
    QString cardNumber = QInputDialog::getText(this, "转账", "请输入你的卡号：", QLineEdit::Normal, "", &ok);
    if (!ok || cardNumber.isEmpty()) return;

    QString password = QInputDialog::getText(this, "转账", "请输入密码：", QLineEdit::Password, "", &ok);
    if (!ok || password.isEmpty()) return;

    QString targetCardNumber = QInputDialog::getText(this, "转账", "请输入目标卡号：", QLineEdit::Normal, "", &ok);
    if (!ok || targetCardNumber.isEmpty()) return;

    double amount = QInputDialog::getDouble(this, "转账", "请输入转账金额：", 0, 0, 1000000, 2, &ok);
    if (!ok) return;

    QJsonObject json;
    json["card_number"] = cardNumber;
    json["password"] = password;
    json["target_card_number"] = targetCardNumber;
    json["amount"] = amount;

    sendRequest("/transfer", json);
}

void MainWindow::handleDeposit()
{
    bool ok;
    QString cardNumber = QInputDialog::getText(this, "存款", "请输入卡号：", QLineEdit::Normal, "", &ok);
    if (!ok || cardNumber.isEmpty()) return;

    QString password = QInputDialog::getText(this, "存款", "请输入密码：", QLineEdit::Password, "", &ok);
    if (!ok || password.isEmpty()) return;

    double amount = QInputDialog::getDouble(this, "存款", "请输入金额：", 0, 0, 1000000, 2, &ok);
    if (!ok) return;

    QJsonObject json;
    json["card_number"] = cardNumber;
    json["password"] = password;
    json["amount"] = amount;

    sendRequest("/deposit", json);
}

void MainWindow::handleWithdraw()
{
    bool ok;
    QString cardNumber = QInputDialog::getText(this, "取款", "请输入卡号：", QLineEdit::Normal, "", &ok);
    if (!ok || cardNumber.isEmpty()) return;

    QString password = QInputDialog::getText(this, "取款", "请输入密码：", QLineEdit::Password, "", &ok);
    if (!ok || password.isEmpty()) return;

    double amount = QInputDialog::getDouble(this, "取款", "请输入金额：", 0, 0, 1000000, 2, &ok);
    if (!ok) return;

    QJsonObject json;
    json["card_number"] = cardNumber;
    json["password"] = password;
    json["amount"] = amount;

    sendRequest("/withdraw", json);
}

void MainWindow::sendRequest(const QString &url, const QJsonObject &json)
{
    QUrl qUrl(QString("http://" + sip + ":" + sport + "%1").arg(url));
    QNetworkRequest request(qUrl);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QJsonDocument doc(json);
    QByteArray data = doc.toJson();

    networkManager->post(request, data);
}

void MainWindow::handleNetworkReply(QNetworkReply* reply)
{
    if (reply->error() == QNetworkReply::NoError)
    {
        QByteArray response = reply->readAll();

        QJsonDocument jsonDoc = QJsonDocument::fromJson(response);
        if (!jsonDoc.isNull() && jsonDoc.isObject())
        {
            QJsonObject jsonObj = jsonDoc.object();
            int code = jsonObj["code"].toInt();
            QString desc = jsonObj["desc"].toString();
            QString data = jsonObj["data"].toString();

            QString resultText;
            if (code == 1) {
                resultText = "操作成功！\n" + data;
            } else {
                resultText = "操作失败！\n" + desc;
            }

            ui->resultTextBox->setPlainText(resultText);
        }
        else
        {
            ui->resultTextBox->setPlainText("Invalid JSON response");
        }
    }
    else
    {
        QMessageBox::critical(this, "Network Error", reply->errorString());
    }

    reply->deleteLater();
}
